const regeneratorRuntime = require("../vendor/regenerator-runtime")
const co = require("../vendor/co")
const CONCUR = 2//并发上传
const url = "https://upload.qiniup.com/";
const cache = new Map()
const ignoreList = new Map()

let _token = null


function make(file) {
    return new Promise((resolve, reject) => {
        if (ignoreList.has(file)) {
            resolve(file)
            return
        }
        const key = new Date().getTime() + Math.ceil(Math.random() * 80000 + 10000);
        if (cache.has(key)) {
            resolve(key)
            return
        }
        console.log("上传中..." + file + "--" + key)
        wx.uploadFile({
            url: url,
            filePath: file,
            name: 'file',
            formData: {
                key,
                token: _token,
            },
            success: res => {
                if (res.statusCode == 200) {
                    resolve(key);
                    cache.set(key, true)
                } else {
                    getApp().wxToast.warn("图片上传失败")
                    reject("上传失败");
                    getApp().post("city/msg/upload-error", {
                        data: { msg: JSON.stringify(res) },
                        showMsg: false
                    })
                }
            },
            fail: res => {
                getApp().wxToast.warn("图片上传失败")
                console.log(res, 'xxxxxxxx');
                reject();
            }
        })
    });
}

function upload(files) {
    if (!files) {
        return Promise.resolve("")
    }
    let arr = [];
    if (typeof files === "string") {
        arr.push(files);
    } else if (files instanceof Array) {
        arr = arr.concat(files);
    } else {
        return Promise.resolve("");
    }
    if (arr.length == 0) {
        return Promise.resolve("");
    }
    let chunk = arr.chunk(CONCUR)
    return co(function* () {
        if (!_token) {
            console.log("no token")
            const td = yield getApp().http.get("city/member/qn-token")
            _token = td.data
        }
        const keys = []
        for (let i = 0; i < chunk.length; i++) {
            const chunkKeys = yield Promise.all(chunk[i].map(o => {
                return make(o)
            }))
            console.log("已上传块：", i)
            keys.push(...chunkKeys)
        }
        console.log(keys)
        return keys
    })
}

function ignore(file) {
    console.log("忽略上传文件:", file)
    ignoreList.set(file, 1)
}
function clearCache() {
    cache.clear()
    ignoreList.clear()
}

module.exports = { upload, ignore, clearCache };